"""
多模型对比功能配置
所有可配置参数集中管理
"""

from typing import Dict, Any
import os
from pydantic import BaseSettings


class ComparisonConfig(BaseSettings):
    """对比功能配置类"""
    
    # 并发控制
    MAX_CONCURRENT_MODELS: int = 4  # 最大并发模型数
    DEFAULT_TIMEOUT: float = 30.0   # 默认超时时间（秒）
    MAX_RETRY_COUNT: int = 1        # 最大重试次数
    USER_CONCURRENCY_LIMIT: int = 3 # 每用户并发任务限制
    
    # 性能配置
    WEBSOCKET_LATENCY_TARGET: int = 100  # WebSocket延迟目标（毫秒）
    REDIS_CACHE_TTL: int = 3600          # Redis缓存TTL（秒）
    RESPONSE_TIME_LIMIT: int = 30        # 响应时间限制（秒）
    
    # 评分权重配置
    SCORING_WEIGHTS: Dict[str, float] = {
        "quality": 0.25,
        "relevance": 0.25,
        "creativity": 0.25,
        "fluency": 0.25
    }
    
    # 模型配置
    SUPPORTED_MODELS: Dict[str, Dict[str, Any]] = {
        "gpt-4": {
            "version": "latest",
            "max_tokens": 4096,
            "default_temperature": 0.7,
            "cost_per_1k_tokens": {"input": 0.03, "output": 0.06}
        },
        "gpt-3.5-turbo": {
            "version": "latest",
            "max_tokens": 4096,
            "default_temperature": 0.7,
            "cost_per_1k_tokens": {"input": 0.001, "output": 0.002}
        },
        "qwen-max": {
            "version": "latest",
            "max_tokens": 8192,
            "default_temperature": 0.7,
            "cost_per_1k_tokens": {"input": 0.0008, "output": 0.002}
        },
        "ernie-bot-4": {
            "version": "latest",
            "max_tokens": 4096,
            "default_temperature": 0.7,
            "cost_per_1k_tokens": {"input": 0.001, "output": 0.002}
        },
        "glm-4": {
            "version": "latest",
            "max_tokens": 8192,
            "default_temperature": 0.7,
            "cost_per_1k_tokens": {"input": 0.001, "output": 0.002}
        }
    }
    
    # MongoDB配置
    MONGODB_COLLECTION_NAME: str = "model_comparisons"
    MONGODB_EVENTS_COLLECTION: str = "comparison_events"
    MONGODB_INDEX_FIELDS: list = ["session_id", "user_id", "created_at"]
    
    # A/B测试配置
    AB_TEST_MIN_SAMPLES: int = 30           # 最小样本数
    AB_TEST_CONFIDENCE_LEVEL: float = 0.95  # 置信水平
    AB_TEST_REPORT_RETENTION_DAYS: int = 90 # 报告保留天数
    
    # WebSocket配置
    WS_HEARTBEAT_INTERVAL: int = 30  # 心跳间隔（秒）
    WS_RECONNECT_MAX_ATTEMPTS: int = 5  # 最大重连次数
    WS_RECONNECT_DELAY: int = 1000  # 重连延迟（毫秒）
    
    # 前端配置
    UI_MAX_MODELS_DISPLAY: int = 4      # 最大显示模型数
    UI_DIFF_ALGORITHM: str = "word"     # 差异算法（word/char/line）
    UI_SYNC_SCROLL_ENABLED: bool = True # 同步滚动
    UI_MOBILE_BREAKPOINT: int = 768     # 移动端断点（像素）
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    
    class Config:
        """Pydantic配置"""
        env_prefix = "COMPARISON_"  # 环境变量前缀
        env_file = ".env"           # 环境文件
        env_file_encoding = "utf-8"
        
    @classmethod
    def from_env(cls) -> "ComparisonConfig":
        """从环境变量加载配置"""
        return cls()
    
    def get_model_config(self, model_name: str) -> Dict[str, Any]:
        """获取特定模型的配置"""
        for key, config in self.SUPPORTED_MODELS.items():
            if key in model_name.lower():
                return config
        # 返回默认配置
        return {
            "version": "latest",
            "max_tokens": 4096,
            "default_temperature": 0.7,
            "cost_per_1k_tokens": {"input": 0.002, "output": 0.004}
        }
    
    def validate_weights(self) -> bool:
        """验证评分权重总和为1"""
        total = sum(self.SCORING_WEIGHTS.values())
        return abs(total - 1.0) < 0.001


# 全局配置实例
comparison_config = ComparisonConfig.from_env()